﻿using Guoc.BigMall.Infrastructure.Http;
using Guoc.BigMall.Infrastructure.Log;
using Guoc.BigMall.Infrastructure.Payment;
using Guoc.BigMall.Web.Services;
using Guoc.BigMall.WebService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Guoc.BigMall.Web.Controllers
{
    /// <summary>
    ///  支付
    /// </summary>
    public class PaymentController : Controller
    {
        IPaymentService _payService;
        ILogger _log;
        public PaymentController(ILogger log, IPaymentService payService)
        {
            this._log = log;
            this._payService = payService;
        }
        public ActionResult PaidNotify(string orderCode)
        {
            _payService.PaidNotify(orderCode);
            return new JsonNetResult(ResultModel.Ok());
        }

        public ActionResult Notify()
        {
            // Request.InputStream
            _log.Info("===收到微信回调通知====");
            var resultXml = "";
            try
            {
                if (Request.InputStream == null || Request.InputStream.Length == 0) {
                    _log.Info("===通知内容为空====");
                    _log.Info("===返回微信回调结果====");
                    return Content("", "text/xml");
                }

                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                string req = System.Text.Encoding.UTF8.GetString(byts);
                _log.Info("===通知报文：{0}", req);
                // 处理业务代码 
                _payService.Notify(req);

                AbstractRequest res = new AbstractRequest();
                res.Add("return_code", "SUCCESS");
                res.Add("return_msg", "OK");
                resultXml = res.ToXml();              
            }
            catch (Exception ex)
            {

                AbstractRequest res = new AbstractRequest();
                res.Add("return_code", "FAIL");
                res.Add("return_msg", ex.Message);

                resultXml = res.ToXml();
            }

            // 处理返回微信结果
            _log.Info("===返回微信回调结果====");
            return Content(resultXml, "text/xml");
        }
    }
}